<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>角色管理</title>
<jsp:include page="../inc.jsp"></jsp:include>
	<script type="text/javascript"
	src="${pageContext.request.contextPath}/javascript/comboBoxTree.js"
	charset="utf-8"></script>
<script type="text/javascript">
	/**
	 * 企业管理
	 */

	/* ----------------------- private属性 ----------------------- */
	var gridEl = 'repTime-grid';
	var grid, form, selModel, toolbar;
	var win;
	var tree;
	var searchFlds;
	/* ----------------------- private方法 ----------------------- */
	// 创建列表
	function createGrid() {
		var queryFlds = new Array();
		 searchFlds = new Ext.util.MixedCollection();
		queryFlds.push('name');
		var fldTimeName = new Ext.form.TextField({
			name : 'name',
			id : gridEl + '-name',
			fieldLabel : '时间段名称',
			allowBlank : true,
			width : 200
		});

		searchFlds.add('name', fldTimeName);
		grid = Ext.create('gridView', {
			remoteSort : true,
			gridId : gridEl,
			checkboxSelectionModel : true,
			queryFlds : queryFlds,
			searchFlds : searchFlds,
			entityClassName : 'com.rover.entity.system.Role',
			queryUrl : '../roleController/query.action',
			deleteUrl : '../roleController/delete.action',
			jsonId : 'id',
			recordPk : [ "id" ]
			
		});
		selModel = grid.getSelectionModel();
		selModel.on('select', onRowSelect);
	}

	// 选择某行
	function onRowSelect(selModel,record , rowIndex, eOpts) {
		var data = record.data;
		tree.store.load({params:{'roleId':data.id,'sAdmin':data.sAdmin}});
	}

	// 刷新列表
	function reloadRecords() {
		grid.getStore().reload();
	}

	function createForm() {
		Ext.define('roleForm', {
			extend : 'Ext.form.Panel',
			fields : new Ext.util.MixedCollection(),
			initComponent : function() {
				var me = this;
				var tn = 1;

				this.fields.add("id", new Ext.form.Hidden({
					name : "id",
					dataIndex : "id"
				}));
				this.fields.add("resources", new Ext.form.Hidden({
					name : "resources",
					dataIndex : "resources"
				}));
				
				this.fields.add("name", new Ext.form.TextField({
					name : "name",
					dataIndex : "name",
					fieldLabel : "角色名称",
					allowBlank : false
				}));
				this.fields.add("description", new Ext.form.TextField({
					name : "description",
					dataIndex : "description",
					fieldLabel : "描述",
					allowBlank : true
				}));
				this.fields.add("roleResource",Ext.create("comboBoxTree", {  
			        id : 'roleResource',  
			        name : 'roleResource',  
			        hiddenValue : '',
			        hiddenName : 'id',// 提交到后台的input的name ，对应下面store里的''id，必须要填
			        storeUrl : '../resourceController/getAllResource.action',  
			        cascade : 'both',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联  
			      //  checkModel:'double',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选  
			        width : 270,  
			        fieldLabel : '资源',  
			        allowBlank : true,
			        labelWidth : 60,  
			        rootId : 'root-0',  //后天添加数据的时候root不计算在呢
			        rootText : '全部',  
			        treeNodeParameter : ''
			      
			    }));
				this.items = [ {
					layout : "form",
					columnWidth : 1,
					labelAlign : "right",
					labelWidth : 100,
					items : [ this.fields.get("id"), this.fields.get("resources"),this.fields.get("name"),
							this.fields.get("description"),this.fields.get("roleResource") ]
				} ];
				this.frame = true;
				this.layout = 'fit';
				this.region = 'east';
				this.border = true;
				this.split = true;
				this.callParent(arguments);
			}
			,
			onRender : function() {
				this.callParent(arguments);
			},
			newDataRecord : function() {
				this.fields.get("id").setValue('');
				this.fields.get("name").setValue('');
				this.fields.get("description").setValue('');
				this.fields.get("resources").setValue('');
				this.fields.get("roleResource").setValue('');
				this.fields.get("roleResource").setRawValue('');
			}

		});
	}

	// 修改的记录，初始化表单
	function EditRecord() {
		var sm = grid.getSelectionModel();
		var records = sm.getSelection();
		
		if (records.length <= 0) {
			Ext.Msg.alert('错误', "未选中记录，不能修改！");
			return;
		}
		var data = records[0].data;
		form.getForm().findField('id').setValue(data.id);
		form.getForm().findField('name').setValue(data.name);
		form.getForm().findField('description').setValue(data.description);
		createWindows();
		
		
		Ext.Ajax.request({
			url : "../roleController/getRoleResource.action",
			method : "POST",
			params : {
				id : data.id
			},
			callback : function(o, s, r) {
				var respText = Ext.decode(r.responseText);
				if (respText.success) {
					var arr=respText.data;
					form.getForm().findField("roleResource").picker.getRootNode();
					form.getForm().findField("roleResource").picker.getRootNode().eachChild(function(child){
						checkNode(child,respText.data);
					});
					var varValue='',varName='';
					for(var i=0,n=arr.length;i<n;i++){
						varName+=arr[i][0]+";";
						varValue+=arr[i][1]+";";
					}
					form.getForm().findField("roleResource").hiddenValue=varValue;
					form.getForm().findField("roleResource").setValue(varName);
				}
			}
		});
	}
    function setCheck(chk){
    	form.getForm().findField("roleResource").picker.getRootNode().eachChild(function(child){
    		UncheckNode(child,chk);
		});
    }
	function UncheckNode(node,chk){
		node.set('checked',chk);
		if(node.isNode){
			node.eachChild(function(child){
				UncheckNode(child,chk);
			});
		}
	}
	function checkNode(node,arr){
		for(var i=0,n=arr.length;i<n;i++){
			if(node.data.id==arr[i][1]){
				node.set('checked',true);
				break;
			}
		}
		if(node.isNode){
			node.eachChild(function(child){
				checkNode(child,arr);
			});
		}
	}
	
	function createWindows() {
		if (win == null) {
			
			win = new Ext.Window({
				title : '新增',
				iconCls : 'icon-win',
				autoHeight : true,
				width : 335,
				height : 200,
				buttonAlign : 'center',
				buttons : [ {
					text : "保存",
					handler : function() {
						if (form.getForm().isValid()) {
							form.getForm().findField("resources").setValue(form.getForm().findField("roleResource").hiddenValue);
							form.getForm().submit({
								url : '../roleController/save.action',
								scope : form,
								success : function(form, action) {
									win.hide();
									grid.getStore().reload();
									grid.getSelectionModel().clearSelections();
								},
								failure : function(form, action) {
									 if (action.result.message == undefined)
									      Ext.Msg.alert('错误', '网络连接失败.');
									    else
									      Ext.Msg.alert('错误', action.result.message);
								},
								waitMsg : '保存数据...'
							});
						} else {
							Ext.Msg.alert('提示', '表单含有无效或空数据');
						}
					},
					id : "btnSave"
				}, {
					text : "关闭",
					id : "btnClose",
					handler : function() {
						win.hide();
					}
				} ],
				layout : 'fit',
				plain : false,
				closable : false,
				modal : true,
				items : [ form ]
			});
		}
		win.show();

	}



	// 新建或修改表单成功提交后,重新加载其父节点
	function afterCommitFormSuccess(operation, recordData) {
		onWinHide();
		grid.getStore().reload();
	}
	function createRnRTree() {
		 var store = Ext.create('Ext.data.TreeStore', {
		        proxy: {
		            type: 'ajax',
		            actionMethods: 'post',
		            url : "../resourceController/getRoleResource.action"
		        },
		        root: {
		            text: '根节点',
		            id: '0',
		            expanded: true
		        },
		        folderSort: true,
		        sorters: [{
		            property: 'text',
		            direction: 'ASC'
		        }]
		    });
		 
		     tree = Ext.create('Ext.tree.Panel', {
		        store: store,
		        rootVisible:false,
		        viewConfig: {
		            plugins: {
		                ptype: 'treeviewdragdrop'
		            }
		        },
		        autoHeight:true,
		        width: 250,
		        title: '权限',
		        useArrows: true,
		        dockedItems: [{
		            xtype: 'toolbar',
		            items: [{
		                text: '展开',
		                handler: function(){
		                    tree.expandAll();
		                }
		            }, {
		                text: '收缩',
		                handler: function(){
		                    tree.collapseAll();
		                }
		            }]
		        }]
		    });
	}
	// 创建layout
	function createLayout() {
		var filed1 = new Ext.form.Field();
		toolbar = new Ext.Toolbar({
			items : [  {
				text : "新增",
				iconCls : 'addIcon',
				id : "tlb_NEW",
				handler : function() {
					form.newDataRecord();
					setCheck(false);
					createWindows();
				}
			}, '-', {
				text : "编辑",
				iconCls : 'editIcon',
				id : "tlb_EDIT",
				handler : function() {
					setCheck(false);
					EditRecord();
				}
			}, '-', {
				iconCls : 'deleteIcon',
				text : "删除",
				id : "tlb_DELETE",
				handler : function() {
					grid.deleteRecord();
				}
			}, "->",  searchFlds.get("name"), {
		        text: "搜索",
		        iconCls : 'searchIcon',
		        handler: function () {
		        	grid.load();
		        }
		    } ]
		});

		var viewport = new Ext.Viewport({
			layout : 'border',
			items : [  {
				layout : 'border',
				region : 'center',
				border : false,
				items : [ {
					layout : 'fit',
					region : 'north',
					border : false,
					items : [ toolbar ],
					height : 25
				},grid ]
			} , {
				layout : 'fit',
				region : 'east',
				border : false,
				items : [tree]
			} ]
		});
		viewport.doLayout();
	}

	Ext.onReady(function() {
		Ext.QuickTips.init();
		createGrid();
		createForm();
		createRnRTree();
		createLayout();
		form = Ext.create('roleForm');
		//初始化数据
		form.getForm().findField("roleResource").createPicker();
	});
</script>
</head>
<body>

</body>
</html>